package cn.edu.henu.team.ui_test;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.base.BaseActivity;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.upLog;
import cn.edu.henu.team.utils.CircleTransform;
import cn.edu.henu.team.utils.myImageLoader;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class UpLoadLogActivity extends BaseActivity{
    @BindView(R.id.back1)
    ImageView back;
    @BindView(R.id.publish)
    TextView publish;
    @BindView(R.id.ed1)
    EditText ed1;
    @BindView(R.id.ed2)
    EditText ed2;
    @BindView(R.id.ed3)
    EditText ed3;
    @BindView(R.id.ed4)
    EditText ed4;
    @BindView(R.id.ed5)
    EditText ed5;
    private GridView publishGridView;
    private GridAdapter gridAdapter;
    private ArrayList<ImageItem> imageItems;
    private int size=0;

    private String str1="", str2="", str3="", str4="", str5="";

    @Override
    protected int initLayout() {
        return R.layout.activity_up_load_log;
    }

    @Override
    protected void initView() {
        publishGridView = findViewById(R.id.publishGridView);
        gridAdapter = new GridAdapter();
        publishGridView.setAdapter(gridAdapter);
    }

    @Override
    protected void initData() {
    }

    @OnClick({R.id.publish,R.id.back1})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back1:
                finish();
                break;
            case R.id.publish:
                str1 = ed1.getText().toString();
                str2 = ed2.getText().toString();
                str3 = ed3.getText().toString();
                str4 = ed4.getText().toString();
                str5 = ed5.getText().toString();
                _User user = BmobUser.getCurrentUser(_User.class);

                final ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setCancelable(true);
                progressDialog.setMessage("正在发布中...");
                progressDialog.show();
                final upLog mUpLog = new upLog();
                mUpLog.setTime(str1);
                mUpLog.setLocation(str2);
                mUpLog.setAdministration(str3);
                mUpLog.setContent(str4);
                mUpLog.setAnswer(str5);
                mUpLog.setUser(user);
                mUpLog.setUserID(user.getObjectId());
                if (size == 0) {
                    mUpLog.setHaveIcon(false);
                    mUpLog.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if(e==null){
                                Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                                progressDialog.dismiss();
                                finish();
                            }else{
                                Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
                                progressDialog.dismiss();
                            }
                        }
                    });
                }else{
                    size=0;
                    final String[] filePaths = new String[imageItems.size()];
                    for (int i = 0; i < imageItems.size(); i++) {
                        filePaths[i] = imageItems.get(i).path;
                    }

                    BmobFile.uploadBatch(filePaths, new UploadBatchListener() {
                        @Override
                        public void onSuccess(List<BmobFile> list, List<String> list1) {
                            if(list1.size() == filePaths.length){
                                mUpLog.setHaveIcon(true);
                                mUpLog.setHeadImgUrl(list1);
                                mUpLog.save(new SaveListener<String>() {
                                    @Override
                                    public void done(String s, BmobException e) {
                                        if(e==null){
                                            Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
                                            progressDialog.dismiss();
                                            finish();
                                        }else{
                                            Toast.makeText(getApplicationContext(), "上传失败", Toast.LENGTH_SHORT).show();
                                            progressDialog.dismiss();
                                        }
                                    }
                                });
                            }
                        }

                        @Override
                        public void onProgress(int i, int i1, int i2, int i3) {
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onError(int i, String s) {
                            progressDialog.dismiss();
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                gridAdapter.notifyDataSetChanged();
                size=imageItems.size();
            } else {
               showToastInThread(getApplicationContext(),"没有选择图片");
            }
        }
    }
    private class GridAdapter extends BaseAdapter {
        public GridAdapter() {
        }

        @Override
        public int getCount() {
            if (imageItems == null)
                return 1;
            else
                return imageItems.size()+1;
        }

        @Override
        public Object getItem(int i) {
            return imageItems.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            GridAdapter.ViewHolder holder = null;
            if (view == null) {
                holder = new GridAdapter.ViewHolder();
                view = LayoutInflater.from(UpLoadLogActivity.this).inflate(R.layout.grid_layout, null);
                holder.image_voice = view.findViewById(R.id.gird_img);
                view.setTag(holder);
            } else {
                holder = (GridAdapter.ViewHolder) view.getTag();
            }
            if (imageItems == null) {
                holder.image_voice.setImageResource(R.mipmap.add_icon);
            } else {
                if (i == imageItems.size()) {
                    holder.image_voice.setImageResource(R.mipmap.add_icon);
                } else {
                    File file = new File(imageItems.get(i).path);
                    if (file.exists()) {
                        Bitmap bm = BitmapFactory.decodeFile(imageItems.get(i).path);
                        holder.image_voice.setImageBitmap(CircleTransform.centerSquareScaleBitmap(bm,100));
                    }
                }
            }
            holder.image_voice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ((imageItems != null && i == imageItems.size()) || imageItems == null) {
                        addImage();
                    }
                }
            });
            return view;
        }

        class ViewHolder {
            private ImageView image_voice;
        }
    }
    /**
     * 添加图片哦
     */
    private void addImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(true);   //多选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setSelectLimit(6);    //最多选择X张
        imagePicker.setCrop(false);       //不进行裁剪
        Intent intent = new Intent(UpLoadLogActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }
}